package com.reach.redis.interceptor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.reach.redis.annotation.Cacheable;
import com.reach.redis.aspect.CacheAspect;
import com.reach.redis.bo.CacheConfig;
import com.reach.redis.manager.SpringContextUtil;
import com.reach.redis.utils.JsonUtil;
 
/**
 * 缓存拦截
 */
public class QueryCacheInterceptor extends AbstractCacheInterceptor  {
	
	private static final Logger logger = LoggerFactory.getLogger(QueryCacheInterceptor.class);

	public Object intercept(MethodInvocation invo,CacheConfig cacheConfig) throws Throwable {
		
		if(logger.isDebugEnabled()) {
			logger.debug("Cache intercept query  class [{}], method [{}],args [{}].",invo.getThis().getClass().getName(),invo.getMethod().getName(),String.valueOf(invo.getArguments()));
		}
		
		CacheAspect cacheAspect = (CacheAspect) SpringContextUtil.getBean("cacheAspect");
		final String key =  getKey(invo.getArguments(), cacheConfig);
		if(logger.isDebugEnabled()) {
			logger.debug("redis key is :{}",key);
		}
		final String cacheKey = getFullKey(invo.getArguments(),cacheConfig,key) ;
		if(!isValid(cacheConfig, key)) {
			 return invo.proceed();
		}
		Object cacheValue = cacheAspect.readCache(cacheKey);
		if(cacheValue == null) {
			 Object result = invo.proceed();
			 try {
				 if(isSuccessResult(result)) {
					 cacheAspect.writeCache(result,cacheKey,getExpire(invo.getArguments(),cacheConfig));
				 }
			}catch(Exception e) {
				logger.error(e.getMessage());
			}
			return result;
		}
		return cacheValue;
	}
	
	private boolean isValid(CacheConfig cacheConfig,String key) {
		//如果不需要检查是否必填，直接返回true
		if(!getCache(cacheConfig).required()) {
			return true;
		}
		List<String> list = new ArrayList<>();
		String[] keys = key.split("_");
		for(String k : keys) {
			if(StringUtils.isNotBlank(k) && !"null".equals(k)) {
				list.add(k);
			}
		}
		if(list.size() == getCache(cacheConfig).key().split(",").length) {
			return true;
		}
		return false;
	}
	
	private boolean isSuccessResult(Object obj) {
		try {
			if(obj instanceof String) {
				String code = JsonUtil.getJson(String.valueOf(obj), "code");
				return isTrue(code);
			}
			if(isExists(obj, "code")) {
				Method method = obj.getClass().getMethod("get"+upper("code"));	
				String code =  String.valueOf(method.invoke(obj));
				return isTrue(code);
			}
		}catch(Exception e) {
			logger.error(e.getMessage());
		}
		return true;
	}
	
	private boolean isTrue(String code) {
		if(StringUtils.isEmpty(code)) {
			return true;
		}
		if("1000".equals(code)) {
			return true;
		}else {
			return false;
		}
	}
	
	private boolean isExists(Object obj,String field) {
		Method[]  objArray = obj.getClass().getMethods();
		for(Method v : objArray) {
			if(v.getName().toLowerCase().endsWith(field.toLowerCase())) {
				return true;
			}
		}
		return false;
	}
	

	@Override
	public String[] getAnnotation(CacheConfig cacheConfig) {
		return getTrim(getCache(cacheConfig).key().split(","));
	}
	
	public Cacheable getCache(CacheConfig cacheConfig) {
		Cacheable cacheable = (Cacheable) cacheConfig.getCache();
		return cacheable;
	}

	@Override
	public String getModule(CacheConfig cacheConfig) {
		return getCache(cacheConfig).module();
	}

	@Override
	public String getEvent(CacheConfig cacheConfig) {
		return getCache(cacheConfig).event();
	}

	@Override
	public Integer getExpire(Object[] object,CacheConfig cacheConfig) {
		
		Integer value =  getCache(cacheConfig).expires();
		if(value == null || value <=0) {
			String  key =  getCache(cacheConfig).expiresKey();
			Object  o = getValue(object, cacheConfig, key);
			if(o != null && !"".equals(o)) {
				return Integer.parseInt(String.valueOf(o));
			}
		}
		return value;
	}
 
}